package com.example.demo.service;

import com.example.demo.config.CosProperties;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.ObjectMetadata;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.net.URL;
import java.net.URLConnection;
import java.util.Objects;

@Service
@RequiredArgsConstructor
@Slf4j
public class IMCosService {

    @NonNull
    private final COSClient cosClient;

    @NonNull
    private final CosProperties cosProperties;

    /**
     * COS默认访问域名
     */
    private static final String COS_DOMAIN = "https://%s.cos.%s.myqcloud.com/";

    @AllArgsConstructor
    @Getter
    public enum FileType {
        IMAGE("image/im/"),
        FILE("file/im/"),
        VIDEO("video/im/"),
        AUDIO("audio/im/");

        /**
         * 上传路径前缀
         */
        private String prefix;
    }

    public Object listBuckets() {
        return this.cosClient.listBuckets();
    }

    public String upload(String url, FileType type) {
        String filename = StringUtils.substring(url, url.lastIndexOf("/") + 1);
        String prefix = type.getPrefix();

        try {
            URLConnection connection = new URL(url).openConnection();
            connection.getContentLength();
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(connection.getContentType());
            metadata.setContentLength(connection.getContentLengthLong());
            if (!Objects.isNull(connection.getContentEncoding())) {
                metadata.setContentEncoding(connection.getContentEncoding());
            }
            this.cosClient.putObject(this.cosProperties.getBucket(), prefix + filename, connection.getInputStream(), metadata);
        } catch (Exception e) {
            // 上传失败
            log.error("文件【{}】上传失败：", url, e);
            return "";
        }
        return String.format(COS_DOMAIN, this.cosProperties.getBucket(), this.cosProperties.getRegion()) + prefix + filename;
    }
}
